<template>
  <vxe-table border ref="xTable1" class="sortable-row-demo" :row-config="{ useKey: true }" :scroll-y="{ enabled: false }" :data="tableData">
    <vxe-column width="60">
      <template #default>
        <span class="drag-btn">
          <i class="vxe-icon--menu"></i>
        </span>
      </template>
      <template #header>
        <vxe-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
          <i class="vxe-icon--question" @click="showHelpTip1 = !showHelpTip1"></i>
        </vxe-tooltip>
      </template>
    </vxe-column>
    <vxe-column field="name" title="Name"></vxe-column>
    <vxe-column field="sex" title="Sex"></vxe-column>
    <vxe-column field="age" title="Age"></vxe-column>
    <vxe-column field="address" title="Address" show-overflow></vxe-column>
  </vxe-table>
</template>
<script>
import Sortable from 'sortablejs';
import XEUtils from 'xe-utils';

export default {
  data() {
    return {
      showHelpTip1: false,
      tableData: [
        { id: 10001, name: 'Test1', nickname: 'T1', role: 'Develop', sex: 'Man', age: 28, address: 'Shenzhen' },
        { id: 10002, name: 'Test2', nickname: 'T2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
        { id: 10003, name: 'Test3', nickname: 'T3', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
        { id: 10004, name: 'Test4', nickname: 'T4', role: 'Designer', sex: 'Women', age: 23, address: 'Shenzhen' },
        { id: 10005, name: 'Test5', nickname: 'T5', role: 'Develop', sex: 'Women', age: 30, address: 'Shanghai' }
      ]
    };
  },
  created() {
    this.rowDrop();
  },
  beforeDestroy() {
    if (this.sortable1) {
      this.sortable1.destroy();
    }
  },
  methods: {
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable1;
        this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          onEnd: ({ newIndex, oldIndex }) => {
            const currRow = this.tableData.splice(oldIndex, 1)[0];
            this.tableData.splice(newIndex, 0, currRow);
          }
        });
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.sortable-row-demo .drag-btn {
  cursor: move;
  font-size: 12px;
}
.sortable-row-demo .vxe-body--row.sortable-ghost,
.sortable-row-demo .vxe-body--row.sortable-chosen {
  background-color: #dfecfb;
}
</style>
